using UnityEngine;

[RequireComponent(typeof(Collider))]
public class ZooSmartPlatform : MonoBehaviour
{
    private Collider platformCollider;
    private bool playerInside = false;
    private bool collisionEnabled = true;

    private Rigidbody playerRb;

    void Start()
    {
        platformCollider = GetComponent<Collider>();

        // Reference the player's rigidbody (from ZooCharacterController)
        if (ZooCharacterController.instance != null)
            playerRb = ZooCharacterController.instance.GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (playerRb == null) return;

        float verticalSpeed = playerRb.linearVelocity.y;

        if (verticalSpeed > 0.1f)
        {
            // Player jumping up, disable collision
            if (collisionEnabled)
                SetCollision(false);
        }
        else if (verticalSpeed <= 0f && !playerInside)
        {
            // Player falling down, enable collision (if not inside)
            if (!collisionEnabled)
                SetCollision(true);
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            playerInside = true;
            Debug.Log("player inside");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            playerInside = false;
            // Safe to re-enable collision when player leaves
            if (playerRb != null && playerRb.linearVelocity.y <= 0)
                SetCollision(true);
        }
    }

    private void SetCollision(bool state)
    {
        platformCollider.isTrigger = !state;
        collisionEnabled = state;
    }
}
